/*
 * output.c
 *
 *  Created on: Feb 25, 2012
 *      Author: albert
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include "output.h"

#define SECTOR_SIZE 512
FILE* sector;
int binary;
pthread_mutex_t file_mutex;

void initFiles() {
	int pid, n;
	char pidStr[10]; // max pid 4,194,304
	char *sector_file, *binary_file;
	pthread_mutex_init(&file_mutex, NULL);
	//printf("filename = %s \n", filename);
	pid = getpid();
	n = sprintf(pidStr, "%d", pid);

	// creating sector file name
	sector_file = (char *) malloc(sizeof(char) * (8 + n));
	stpcpy(sector_file, "sectors.");
	strncat(sector_file, pidStr, n + 1);
	printf("a1");
	// creating binary file name
	binary_file = (char *) malloc(sizeof(char) * (6 + n));
	stpcpy(binary_file, "read.");
	strncat(binary_file, pidStr, n + 1);

	printf("writing to %s \n", sector_file);

//	if ((sector = open(sector_file, O_WRONLY | O_CREAT )) < 0) {
//		printf("FATAL: Failed to open file %s. \n", sector_file);
//		printf("%s\n", strerror(errno));
//		exit(-1);
//	}

	sector = fopen(sector_file, "w");

	if ((binary = open(binary_file, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR  )) < 0) {
		printf("FATAL: Failed to open file %s. \n", binary_file);
		printf("%s\n", strerror(errno));
		exit(-1);
	}
}

void outputToFile(int sector_number, unsigned long int * data) {
	int i;
	//fprintf(stderr, "acquiring lock %u %u\n", sector, file_mutex);
	pthread_mutex_lock(&file_mutex);
	//fprintf(stderr, "trying to print %u %u\n", sector, file_mutex);
	fprintf(sector, "%d\n", sector_number);
	//fprintf(stderr, "saved sector number %d %u\n", sector, sector_number);
	if (data != NULL) {
		write(binary, data, SECTOR_SIZE);
	}
	pthread_mutex_unlock(&file_mutex);
	//printf("releasing lock");
}

void closeFiles() {
	fclose(sector);
	close(binary);
}
